const toDoModel = require("../models/toDoModel");
const formatMessage = require("../utils/formatMessage");

// 新增
const add = async (ctx, next) => {
  const res = await toDoModel.add(ctx.request.body);
  ctx.body = formatMessage(200, "成功");
};
// 登入
// const login = async (ctx, res) => {
//   const { username, password } = ctx.request.body;
//   const isRegistered = await userModel.getUsers({ username });
//   // 判断是否存在此用户
//   if (isRegistered && isRegistered.length) {
//     // 判断密码是否正确
//     const checkPass = password === isRegistered[0].password;
//     if (checkPass) {
//       ctx.body = formatMessage(200, "成功", { id: isRegistered[0].id });
//     } else {
//       ctx.status = 500
//       ctx.body = formatMessage(500, "用户名或密码错误");
//     }

//   } else {
//     ctx.body = formatMessage(500, "用户名或密码错误");
//   }
// };
// 获取todo列表
const getToDos = async (ctx, next) => {
  const res = await toDoModel.query(ctx.query);
  if (res.length) {
    ctx.body = formatMessage(200, '成功', { data: res })
  } else {
    ctx.status=500;
    ctx.body = formatMessage(500, '查询出错')
  }
};
//修改用户密码
const updatePassword = async (req, res) => {
  //用旧密码更新新密码
  let { username, oldPassword, newPassword } = req.body;
  let isUnique = await findUser({ username });
  if (isUnique.length) {
    //表存在该用户
    let hashPassword = isUnique[0].password;
    if (verify) {
      //密码比对成功
      let salt = 10;

      //声明更新条件
      let query = { username };
      let updated = { $set: { password: newHashPassword } };
      let updateResult = await updateUserInfo(query, updated);
      if (updateResult.n) {
        res.send({ httpStatus: 200, msg: "密码修改成功" });
      } else {
        res.send({ httpStatus: 400, msg: "密码修改出错" });
      }
    } else {
      res.send({ httpStatus: 400, msg: "旧密码有误" });
    }
  } else {
    res.send({ httpStatus: 400, msg: "该用户不存在" });
  }
};

const uploadAvatar = async (req, res, next) => {
  const { id } = req.body;
  let updated = { $set: { avatar: req.body.avatarUrl } };
  let result = await updateUserInfo({ id }, updated);
  if (result.n) {
    res.send({ httpStatus: 200, msg: "图片上传成功" });
    next();
  } else {
    res.send({ httpStatus: 400, msg: "图片上传失败" });
    // next();
  }
  next();
};
//退出
const quit = (req, res) => {
  req.session.destroy();
  res.send({ httpStatus: 200, msg: "退出登入" });
};
module.exports = {
  add,
  getToDos,
};
